package com.ruoyi.web.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.system.SysRole;
import com.ruoyi.common.core.domain.entity.system.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.*;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.miniprogram.WxAccessTokenUtils;
import com.ruoyi.common.utils.uuid.ShortIdUtils;
import com.ruoyi.manager.AsyncManager;
import com.ruoyi.manager.factory.AsyncFactory;
import com.ruoyi.security.context.AuthenticationContextHolder;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Slf4j
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Value("${miniprogram.appId}")
    private String appId;

    @Value("${miniprogram.appSecret}")
    private String appSecret;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 如下方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 小程序用户登录。无需进行springsecurity权限校验，因为微信小程序用户由微信官方进行鉴权，无需后端验证其用户名和密码。
     *
     * @param code
     * @return
     */
    @Transactional
    public Map<String, String> loginMiniProgram(String code, String phone) {
        String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", appId, appSecret, code);
        String result = HttpUtils.sendGet(url);
        log.info("loginMiniProgram result: {}", result); // 示例：result: {"session_key":"Mrmcdkhxm3ltbk5md2tj1g==","openid":"owVPG5edQz9uaZqo7XxVP2cdHt7E"}
        //openid是用户在这个小程序上唯一的id，不同小程序用户的id都不一样，session_key是用户的会话信息记录。
        //openid是用户的唯一标识，所以可以判断session中是否存有openid，如果有我们才返回一个token回去。
        JSONObject jsonObject = JSONObject.parseObject(result);

        if (Objects.isNull(jsonObject) || StringUtils.isEmpty(jsonObject.getString("openid")))
            throw new ServiceException("鉴权失败,获取openid为空.", HttpStatus.UNAUTHORIZED);

        String sessionKey = jsonObject.getString("session_key");
        String openid = jsonObject.getString("openid");

        LoginUser loginUser = new LoginUser();
        SysUser sysUser = sysUserMapper.selectMiniUserByOpenId(jsonObject.getString("openid"));
        if (Objects.isNull(sysUser)) { //用户首次登录
            //新建用户并保存到数据库
            sysUser = new SysUser();
//            long userId = IdUtil.getSnowflakeNextId(); //示例：1683677188406980608, 共19位
            long userId = ShortIdUtils.generateUserId();
            sysUser.setUserId(userId);
            sysUser.setUserName("wx_" + userId);
            sysUser.setNickName("微信用户");
            sysUser.setPhonenumber(phone);
            sysUser.setSessionKey(sessionKey);
            sysUser.setOpenId(openid);
            sysUserMapper.insertUser(sysUser);
            //关联用户角色为"小程序用户"
            sysUserRoleMapper.insertMiniprogramUserRole(userId, 4L);
        } else {
            //此处登录的手机号码与数据库中已保存的手机号码不一致，需更新数据库中的手机号码
            if (!phone.equals(sysUser.getPhonenumber())) {
                sysUser.setPhonenumber(phone);
                sysUserMapper.updatePhoneNum(sysUser);
            }
        }

        loginUser.setUserId(sysUser.getUserId());

        //设置小程序用户角色
        SysRole sysRole = new SysRole();
        sysRole.setRoleId(4L);
        sysRole.setRoleName("小程序用户");
        sysUser.setRoles(Collections.singletonList(sysRole));

        loginUser.setUser(sysUser);

        //获取小程序全局唯一后台接口调用凭据
//        WxAccessTokenUtils.getAccessToken();

        Map<String, String> resultMap = new HashMap<>();
        // 生成token
        String token = tokenService.createTokenForMiniprogramUser(loginUser);
        resultMap.put("token", token);
        resultMap.put("userId", sysUser.getUserId().toString());

        return resultMap;
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            String captcha = CacheUtils.get(CacheConstants.CAPTCHA_CODE_KEY, StringUtils.nvl(uuid, ""), String.class);
            CacheUtils.removeIfPresent(CacheConstants.CAPTCHA_CODE_KEY, StringUtils.nvl(uuid, ""));
            if (captcha == null) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha)) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigValueByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    public Map<String, Object> getPhoneNumberOfMiniUser(String code) {
        Map<String, Object> resultMap = new HashMap<>();
        String wxAccessToken = WxAccessTokenUtils.getWxAccessToken();
        String url = String.format("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s", wxAccessToken);
//        log.info("getPhoneNumberOfMiniUser url: {}", url);
        HttpRequest httpRequest = HttpUtil.createPost(url)
                .contentType("application/json")
                .body(JSONObject.toJSONString(new QueryPhoneNumberObject(code)));
//        log.info("getPhoneNumberOfMiniUser httpRequest:{}", httpRequest);
        HttpResponse response = httpRequest.execute();
//        String result = HttpUtil.post(url, params); //会报参数json格式报错
//        String result = HttpUtils.sendPost(url, "code=" + code); //会报参数json格式报错
        //结果示例：{"errcode":0,"errmsg":"ok","phone_info":{"phoneNumber":"18707180041","purePhoneNumber":"18707180041","countryCode":"86","watermark":{"timestamp":1691751429,"appid":"wx15de247df91a38ae"}}}
//        log.info("getPhoneNumberOfMiniUser result: {}", response);
        String responseBody = response.body();
        if (StringUtils.isNotEmpty(responseBody)) {
            JSONObject resultObject = JSONObject.parseObject(responseBody);
            int errcode = resultObject.getIntValue("errcode");
            String errmsg = resultObject.getString("errmsg");
            if (errcode == 0 && Objects.equals(errmsg, "ok")) {
                JSONObject phoneInfo = resultObject.getJSONObject("phone_info");
                String phoneNumber = phoneInfo.getString("phoneNumber");
                String countryCode = phoneInfo.getString("countryCode");
                resultMap.put("phoneNumber", phoneNumber);
                resultMap.put("countryCode", countryCode);
            }
        }

        return resultMap;
    }


    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    class QueryPhoneNumberObject {
        private String code;
    }
}
